---
import '../../global.css'
import { firestore, Game, getSession } from '../../lib/game-saving/account'
import Navbar from '../../components/navbar-main'
import StandardHead from '../../components/standard-head.astro'
import ms from 'ms'
import Button from '../../components/design-system/button'
import { IoLogOutOutline, IoTrashOutline } from 'react-icons/io5'
import { isRandomGameName } from '../../lib/words'

const session = await getSession(Astro.cookies)
if (!session || !session.session.full) return Astro.redirect(`/login?to=${Astro.request.url}`, 302)

const _games = await firestore.collection('games')
	.where('ownerId', '==', session.user.id)
	.orderBy('modifiedAt', 'desc')
	.get()
const allGames = _games.docs.map(doc => ({ id: doc.id, ...doc.data() } as Game))

let games = allGames.filter(game => !isRandomGameName(game.name))
let unnamedGames = allGames.filter(game => isRandomGameName(game.name))

if (games.length === 0 && unnamedGames.length > 0) {
	games = unnamedGames
	unnamedGames = []
}
---

<html lang='en'>
	<head>
		<StandardHead title='Your Games' />
		
		<script>
			import { theme, switchTheme } from "../../lib/state";
			const currentTheme = localStorage.getItem("theme") ?? localStorage.getItem("isDark") ?? "light"
			theme.value = currentTheme;	
			
			switchTheme(theme.value);
		</script>

		<style>
			body {
				display: flex;
				flex-direction: column;
				overflow: hidden;
			}

			.columns {
				flex: 1;
				overflow: hidden;
				display: flex;
				flex-direction: row-reverse;
			}

			.content {
				flex: 1;
				overflow: auto;
			}

			.games {
				display: grid;
				grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
				gap: 10px;
				margin-top: 14px;
			}

			.game {
				border: 2px solid var(--accent);
				background: var(--bg-surface);
				color: #000000;
				padding: 12px;
				user-select: none;
				flex: 1;
				display: flex;
				flex-direction: column;
				gap: 6px;
				position: relative;
			}

			.game:hover {
				background: var(--accent);
				color: #ffffff;
			}

			.game h3 {
				margin: 0;
				font-size: 1rem;
				white-space: nowrap;
				text-overflow: ellipsis;
				overflow: hidden;
			}

			.game .modified-at {
				margin: 0;
				font-size: 0.8rem;
				color: var(--fg-muted);
			}

			.game:hover .modified-at {
				color: var(--fg-muted-on-accent);
			}

			.game .delete {
				position: absolute;
				top: 6px;
				right: 6px;
				color: var(--fg-muted-on-accent);
				background: none;
				border: none;
				font-size: inherit;
				display: none;
				padding: 0;
				font-size: 18px;
			}

			.game:hover .delete {
				display: block;
			}

			.game .delete:hover {
				color: #ffffff;
			}

			.content h2 {
				margin: 0;
				margin-top: 50px;
			}

			.content p {
				margin: 0;
				margin-top: 16px;
    			margin-bottom: 18px;
			}

			.sidebar {
				background: var(--bg-floating);
				color: #ffffff;
				width: 300px;
				padding: 20px;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				line-height: var(--line-height-copy);
				height: 100%;
			}

			.sidebar-section {
				display: flex;
				flex-direction: column;
				gap: 14px;
			}

			.sidebar h3 {
				margin: 0;
				font-size: 1.3rem;
			}

			.sidebar p, .sidebar ul {
				margin: 0;
				font-size: 0.9rem;
			}

			.sidebar ul {
				padding-left: 0;
				list-style-type: none;
			}

			.sidebar li::before {
				content: '- ';
			}

			.sidebar a.link {
				color: var(--accent-light);
			}

			.sidebar a.link:hover {
				text-decoration: underline;
			}

			.account-strip {
				display: flex;
				flex-direction: row;
				align-items: center;
				gap: 4px;
			}

			.account-strip .email {
				color: var(--fg-muted);
				flex: 1;
				overflow: hidden;
				text-overflow: ellipsis;
			}
			
			.game .title-container{
				display: flex;
				justify-content: space-between;
				max-height: 1.5rem;
			}
			.icon{
				height: 100%;
				width: 1rem;
			}
			.tooltip {
				position: relative;
				display: inline-block;
			}

			.tooltip .tooltip-text {
				visibility: hidden;
				width: 300px;
				background-color: rgba(0, 0, 0, 0.5);
				color: #fff;
				text-align: center;
				border-radius: 6px;
				padding: 5px 0;
				
				/* Position the tooltip */
				position: absolute;
				z-index: 1;
				bottom: 100%;
				left: 50%;
				margin-left: -150px;
			}

			.tooltip:hover .tooltip-text {
				visibility: visible;
			}

			.game:hover .icon-container{
				margin-right:5%
			}
		</style>
	</head>
	<body>
		<Navbar session={session} />

		<div class='columns'>
			<div class='content'>
				<div class='copy-container'>
					<h1>Your Games</h1>

					{games.length === 0 ? (
						<p style={{ color: 'var(--fg-muted)'}}>
							It's all spooky and empty here. <a href='/~/new-game'>Make a game already!</a>
						</p>
					) : null}
					<div class='games'>
						{games.map(game => (
							<a class='game' href={`/~/${game.id}`}>
								<div class="title-container">
									<h3>{game.name || 'Untitled'}</h3>
									<div class="icon-container">
										{game.isRoomOpen && 
											<div class="tooltip">
												<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="icon">
												<path d="M9 12C9 13.3807 7.88071 14.5 6.5 14.5C5.11929 14.5 4 13.3807 4 12C4 10.6193 5.11929 9.5 6.5 9.5C7.88071 9.5 9 10.6193 9 12Z" stroke="#000000" stroke-width="1.5"/>
												<path d="M14 6.5L9 10" stroke="#000000" stroke-width="1.5" stroke-linecap="round"/>
												<path d="M14 17.5L9 14" stroke="#000000" stroke-width="1.5" stroke-linecap="round"/>
												<path d="M19 18.5C19 19.8807 17.8807 21 16.5 21C15.1193 21 14 19.8807 14 18.5C14 17.1193 15.1193 16 16.5 16C17.8807 16 19 17.1193 19 18.5Z" stroke="#000000" stroke-width="1.5"/>
												<path d="M19 5.5C19 6.88071 17.8807 8 16.5 8C15.1193 8 14 6.88071 14 5.5C14 4.11929 15.1193 3 16.5 3C17.8807 3 19 4.11929 19 5.5Z" stroke="#000000" stroke-width="1.5"/>
												</svg>
												<p class="tooltip-text">This game has collab features enabled and has been shared</p>
											</div>
										}
										{game.isSavedOnBackend && 
											<div class="tooltip">
												<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="icon">
												<path d="M4 18V6" stroke="#000000" stroke-width="1.5" stroke-linecap="round"/>
												<path d="M20 12L20 18" stroke="#000000" stroke-width="1.5" stroke-linecap="round"/>
												<path d="M12 10C16.4183 10 20 8.20914 20 6C20 3.79086 16.4183 2 12 2C7.58172 2 4 3.79086 4 6C4 8.20914 7.58172 10 12 10Z" stroke="#000000" stroke-width="1.5"/>
												<path d="M20 12C20 14.2091 16.4183 16 12 16C7.58172 16 4 14.2091 4 12" stroke="#000000" stroke-width="1.5" stroke-linecap="round"/>
												<path d="M20 18C20 20.2091 16.4183 22 12 22C7.58172 22 4 20.2091 4 18" stroke="#000000" stroke-width="1.5"/>
												</svg>
												<p class="tooltip-text">This game is saved on the backend and collab features are available</p>
											</div>
										}
										
									</div>	
								</div>
								<p class='modified-at'>
									Edited {ms(Math.max(Date.now() - game.modifiedAt.toMillis(), 1000), { long: true })} ago
								</p>
								<button class='delete' data-id={game.id} data-name={game.name || 'Untitled'}>
									<IoTrashOutline />
								</button>
							</a>
						))}
					</div>

					{unnamedGames.length > 0 ? (
						<div class='unnamed'>
							<h2>Unnamed games</h2>
							<div class='games'>
								{unnamedGames.map(game => (
									<a class='game' href={`/~/${game.id}`}>
										<h3>{game.name || 'Untitled'}</h3>
										<p class='modified-at'>
											Edited {ms(Math.max(Date.now() - game.modifiedAt.toMillis(), 1000), { long: true })} ago
										</p>
										<button class='delete' data-id={game.id} data-name={game.name || 'Untitled'}>
											<IoTrashOutline />
										</button>
									</a>
								))}
							</div>
						</div>
					) : null}
				</div>
			</div>

			<div class='sidebar'>
				<div class='sidebar-section'>
					<h3>Welcome to Sprig!</h3>
					<p>You have {allGames.length} {allGames.length === 1 ? 'game' : 'games'}, {games.length || 'none'} of which {games.length === 1 ? 'has' : 'have'} a name. You've been using Sprig for {ms(Date.now() - session.user.createdAt.toMillis(), { long: true })} so far.</p>
					<p>You might want to...</p>
					<ul>
						<li><a href='/gallery/getting_started' target='_blank' class='link'>Check out the Sprig tutorial</a></li>
						<li><a href='https://github.com/hackclub/sprig/blob/main/docs/docs.md' target='_blank' class='link'>Read our documentation</a></li>
						<li><a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript' target='_blank' class='link'>Learn more JavaScript</a></li>
					</ul>
				</div>

				<div class='sidebar-section'>
					<p>Visit <a href='/migrate' class='link'>the migration page</a> to move legacy Sprig games to your account from this computer.</p>
					<div class='account-strip'>
						<p class='email'>{session.user.email}</p>
						<a href='/logout'><Button icon={IoLogOutOutline}>Log out</Button></a>
					</div>
				</div>
			</div>
		</div>

		<script>
			document.body.addEventListener('click', async (event) => {
				const deleteBtn = event.composedPath().find(item => item instanceof HTMLElement && item.matches('.delete')) as HTMLElement | undefined
				if (!deleteBtn) return
				event.preventDefault()
				const gameId = deleteBtn.dataset.id!
				const gameName = deleteBtn.dataset.name!
				if (!confirm(`Are you sure you want to delete "${gameName}"?`)) return
				deleteBtn.closest('.game')!.remove()

				const res = await fetch(`/api/games/delete`, {
					method: 'POST',
					headers: { 'Content-Type': 'application/json' },
					body: JSON.stringify({ gameId })
				})
				if (!res.ok) console.error(`Error deleting game: ${await res.text()}`)
			})
		</script>
	</body>
</html>